<%@ page language="java" import="java.sql.*" pageEncoding="utf-8"%>

<html>
<head>
    <title>整表查询数据</title>
    <!-- 声明变量：接收查询语句返回的结果 -->
    <%! ResultSet rs; %>
    <%
        String dbName = "studb";
        String userName = "root";
        String userPassword = "123456";
        String url = "jdbc:mysql://localhost/"+
                dbName+"?user="+userName
                +"&password="+userPassword;
        //1、加载JDBC驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2、连接数据库
        Connection conn =DriverManager.getConnection(url);
        //通过数组模拟成批量数据
        String[] numbers = new String[]{"007","008","009","010"};
        String[] names = new String[]{"赵博","王松","张蕾","王哲"};
        String[] birthdays = new String[]{"1989-11-01","1989-11-01","1989-11-03","1989-11-04"};
        String[] stuclass = new String[]{"软件S16-1班","软件S16-2班","软件S16-3班","软件S16-4班"};
        //3、定义SQL语句（向student表中插入数据，？代表预留参数）
        String sql = "INSERT  into student values(?,?,?,?)";
        //4、创建语句对象，用来执行SQL语句
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        for(int i=0; i<4; i++){
            preparedStatement.setString(1, numbers[i]);
            preparedStatement.setString(2, names[i]);
            preparedStatement.setString(3, birthdays[i]);
            preparedStatement.setString(4, stuclass[i]);
            preparedStatement.addBatch();
        }
        int[] result = preparedStatement.executeBatch();
        if(result.length > 0){
            out.print("<script type='text/javascript'>alert('删除成功')</script>");
        }else
            out.print("<script type='text/javascript'>alert('删除失败')</script>");
        sql = "SELECT * from student";
        //5、执行sql语句,并将结果存储到rs（ResultSet）变量中
        rs = preparedStatement.executeQuery(sql);
        //6、关闭连接
        //conn.close();
    %>
</head>

<body>
<table border="1">
    <th colspan="4" style="font-size: x-large;alignment: center">学生信息表</th>
    <tr style="text-align: center">
        <td>学号</td>
        <td>姓名</td>
        <td>出生日期</td>
        <td>所在班级</td>
    </tr>
    <%
        //循环遍历rs中数据
        while(rs.next()){
    %>
    <tr style="text-align: center">
        <td><%=rs.getString(1)%></td>
        <td><%=rs.getString(2)%></td>
        <td><%=rs.getString("birthday")%></td>
        <td><%=rs.getString("stuclass")%></td>
    </tr>
    <%}%>

    <%
        //关闭原则：先创建的后关闭
        rs.close();
        preparedStatement.close();
        conn.close();
    %>
</table>
</body>
</html>
